<?php

namespace Controller\OAuth;


class Weibo extends Base {

    private $http_header = array();

    public function actionIndex() {
        $fromUrl = $this->getParam('fromurl', '/');
        $fromUrl = urldecode($fromUrl);
        $code = $this->getParam('code');
        if (!$code) {
           $this->getCode();
        }
        $token = $this->getToken($code, $fromUrl);
        $weiboUserInfo = $this->getWeiboUserInfo($token['access_token'], $token['uid']);
        $openId = $weiboUserInfo['id'];
        $nickname = $weiboUserInfo['name'];
        $photo = $weiboUserInfo['profile_image_url'];
        $sex = $weiboUserInfo['gender'] == 'm' ? \Data\Base::SEX_BOY : \Data\Base::SEX_GIRL;
        $authId = \Business\User::instance()->replaceWeibo($openId, $nickname, $sex, $photo);
        $ip = $this->getIp();
        $userId = \Business\User::instance()->getUserIdByAuthId($authId, $ip);
        $userMask = $this->getUserMask();
        if ($userId) {
            \Business\User::instance()->setUserLoginMask($userMask, $userId, $ip);
            \Lib\Util\Comm::redirect($fromUrl);
        } else {
            \Business\User::instance()->setUserAuthId($userMask, $authId);
            \Lib\Util\Comm::redirect('/Passport/Bind?fromurl=' . urlencode($fromUrl));
        }
    }

    private function getWeiboUserInfo($token, $uid) {
        $url = 'https://api.weibo.com/2/users/show.json';
        $url .= '?access_token=' . $token;
        $url .= '&uid=' . $uid;
        $json = \Lib\Util\Comm::request($url);
        $weiboUserInfo = json_decode($json, true);
        if (!$weiboUserInfo) {
            $this->throwException('获取用户信息失败');
        }
        return $weiboUserInfo;
    }

    private function getCode() {
        $url = 'https://api.weibo.com/oauth2/authorize' .
            '?client_id=' . \Config\OAuth::WEIBO_CLIENT_ID .
            '&redirect_uri=' . urlencode(\Util\Comm::getCurrentUrl()) .
            '&scope=all';
        \Lib\Util\Comm::redirect($url);
    }

    private function getToken($code) {
        $auth = new \SaeTOAuthV2(\Config\OAuth::WEIBO_CLIENT_ID, \Config\OAuth::WEIBO_CLIENT_SECRET);
        $keys = array();
        $keys['code'] = $_REQUEST['code'];
        $keys['redirect_uri'] = \Util\Comm::getCurrentUrl();
        $token = $auth->getAccessToken('code', $keys);
        return $token;
    }
}